<script setup>
import { checkCodeService, createCodeService } from '@/api/common.js'
import '@/assets/common/common.scss'
import '@/assets/common/el-form-label-center.scss'
import { ref } from 'vue'
import { toPhoto } from '@/utils/base64Utils.js'
import logo from '@/assets/logo.png'
import { ErrorPicture, Refresh, Return, Avatar } from '@icon-park/vue-next'
import { registerService } from '@/api/user.js'
import { successMsg } from '@/utils/sendMsgUtils.js'
import { useRouter } from 'vue-router'
import { encryption } from '@/utils/md5Utils.js'


const router = useRouter()

// 生成验证码图片
const photo = ref('')
const isSpinning = ref(false) // 控制旋转状态

const createCode = async () => {
  if (isSpinning.value) return // 防止重复点击
  isSpinning.value = true // 开始旋转

  const resp = await createCodeService()
  if (resp.code === 1) {
    photo.value = toPhoto(resp.data)
  }

  setTimeout(() => {
    isSpinning.value = false // 停止旋转
  }, 1000) // 控制旋转时间
}
createCode()

const user = ref({
  username: '',
  password: '',
  tPassword: '',
  email: '',
  code: ''
})
// 表单数据


// 校验规则
const rules = ref({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 3, max: 15, message: '用户名长度3-15字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' }
  ],
  tPassword: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, message: '密码至少6位', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        try {
          if (value === user.value.password) {
            callback()
          } else {
            callback(new Error('密码不一致'))
          }
        } catch {
          callback(new Error('密码不一致'))
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  code: [{ required: true, message: '验证码不能为空', trigger: 'blur' },
    {
      validator: async (rule, value, callback) => {
        try {
          const resp = await checkCodeService(value)
          if (resp.code !== 1) {
            await createCode()
            callback(new Error('验证码不正确'))
          } else {
            callback()
          }
        } catch {
          await createCode()
          callback(new Error('验证码验证失败'))
        }
      },
      trigger: 'blur'
    }
  ]
})

const formRef = ref()
// 方法：重置表单
const resetForm = async () => {
  await createCode()
  formRef.value?.resetFields()
}

const onSubmit = async () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      user.value.password = encryption(user.value.password)
      const resp = await registerService(user.value)
      if (resp.code === 1) {
        successMsg(resp.data)
        await router.push('/user/login')
      }
    } else {
      console.log('验证失败')
    }
  })
}
</script>

<template>
  <div class="user-page">
    <el-link @click="router.push('/user/login')" :underline="false" class="top-link-left" type="primary">
      <avatar  theme="outline" class="icon-center" :strokeWidth="6" />
      &nbsp;登录
    </el-link>
    <el-link @click="router.push('/')" :underline="false" class="top-link-right" type="primary">
      返回&nbsp;
      <return theme="outline" class="icon-center" :strokeWidth="6" />
    </el-link>
    <div class="user-image-logo">
      <el-image @click="router.push('/')" :src="logo" />
    </div>
    <el-form
      :model="user"
      :rules="rules"
      ref="formRef"
      style="max-width: 400px"
      label-width="auto"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名：" prop="username">
        <el-input placeholder="用户名长度3-15字符" v-model="user.username" />
      </el-form-item>
      <el-form-item label="密码：" prop="password">
        <el-input type="password" placeholder="密码至少六位" v-model="user.password" />
      </el-form-item>
      <el-form-item label="确认密码：" prop="tPassword">
        <el-input type="password" placeholder="密码至少六位" v-model="user.tPassword" />
      </el-form-item>
      <el-form-item label="电子邮箱：" prop="email">
        <el-input placeholder="邮箱不能为空" v-model="user.email" />
      </el-form-item>
      <el-form-item label="验证码：" prop="code">
        <el-image style="border-radius: 5px" :src="photo" @click.prevent="createCode">
          <template #error>
            <div class="image-slot">
              <error-picture theme="outline" size="50" fill="#333" :strokeWidth="2" />
            </div>
          </template>
        </el-image>

        <span class="icon-center" @click.prevent="createCode">
        <refresh :strokeWidth="6" :class="{ spinning: isSpinning }" />&nbsp;看不清，点击换一张。
      </span>

        <br>
        <el-input placeholder="输入正确验证码" style="margin: 5px 0" v-model="user.code" />
      </el-form-item>
      <el-form-item>
        <div style="width: 100%; text-align: center;">
          <el-button size="large" style="margin-right: 35px; width: 90px" @click.prevent="resetForm">清空</el-button>
          <el-button size="large" style="width: 90px" type="primary" @click="onSubmit">注册</el-button>
        </div>

      </el-form-item>
    </el-form>
  </div>


</template>

<style scoped>

.demo-ruleForm {
  width: 400px;
  margin: 0 auto;


  .icon-center {
    margin-left: 5px;
    font-size: 12px;
    font-weight: bold;
    cursor: pointer;
    color: #11659a;
  }
}


</style>
